//
//  AddProductViewController.m
//  Spa
//
//  Created by PangPond on 10/1/2556.
//  Copyright (c) พ.ศ. 2556 innova. All rights reserved.
//

#import "AddProductViewController.h"
#import "Product.h"

@interface AddProductViewController ()

@end

@implementation AddProductViewController

@synthesize databaseUtility = _databaseUtility;
@synthesize fieldName,fieldPrice;
@synthesize addProductCell = _addProductCell;
@synthesize addProductPriceCell = _addProductPriceCell;
@synthesize keyProductName = _keyProductName;
@synthesize keyProductPrice = _keyProductPrice;
@synthesize keyIf;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.databaseUtility = [[DatabaseUtility alloc]initWithDatabaseName:@"Database"];
    self.fieldName.delegate = self;
    self.fieldPrice.delegate = self;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDataSource

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //[self.tableView reloadData];
    [self loadView];
    [self viewDidLoad];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *product = [self.databaseUtility fetchedResultsWithClass:@"Product" withSortDescriptorString:@"name" withPredicateString:[NSString stringWithFormat:@"name == '%@'",self.keyProductName]];
    Product *products = [product lastObject];
    
    if (indexPath.row == 0) {
        static NSString *CellIdentifier = @"AddProductCell";
        
        AddProductCell *cell = (AddProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddProductCell" owner:self options:nil];
            
            cell = self.addProductCell;
            self.addProductCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = products.name;
        
        return cell;
    }else {
        static NSString *CellIdentifier = @"AddProductPriceCell";
        
        AddProductPriceCell *cell = (AddProductPriceCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddProductPriceCell" owner:self options:nil];
            
            cell = self.addProductPriceCell;
            self.addProductPriceCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = products.price;
        
        return cell;
    }

}


-(IBAction)BackButton:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//validation

-(BOOL)validate: (NSString *) candidate{
    NSString *productName = @"[A-Z0-9a-zก-ฮ๑-๙.]{1,50}";
   
    //@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *productNames = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", productName];
    
    
    return [productNames evaluateWithObject:candidate];
}
-(BOOL)validateInt: (NSString *) candidate{
    NSString *productPrice = @"[0-9]{1,50}";
    NSPredicate *productPrices = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", productPrice];
    return [productPrices evaluateWithObject:candidate];
}
-(IBAction)SaveButton:(id)sender{

    if([self validate:[fieldName text]] ==1)
	{
        
        if([self validateInt:[fieldPrice text]] ==1){
            
        
        if (keyIf == @"1") {
            
            NSArray *products = [self.databaseUtility fetchedResultsWithClass:@"Product" withSortDescriptorString:@"name" withPredicateString:[NSString stringWithFormat:@"name == '%@'",self.keyProductName]];
            
            Product *product = [products lastObject];
            product.name =fieldName.text;
            product.price = fieldPrice.text;
            [self.databaseUtility saveContext];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            Product *product = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:self.databaseUtility.managedObjectContext];
            product.name =fieldName.text;
            product.price = fieldPrice.text;
            [self.databaseUtility saveContext];
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"NO1" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
            }

        
	}else{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"NO" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
		[alert show];
	}
    
}
@end
